# LGPO single-value policy template. Configure explicitly before deployment.
# Dot-sourcing -LibraryOnly defines functions only; no registry/native operations.
[CmdletBinding()]
param([ValidateSet('Apply','Remove','Initialize')][string]$Mode='Apply', [switch]$LibraryOnly)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

function New-FwAbsent { [pscustomobject][ordered]@{ Exists=$false; Type=0; Data='' } }
function ConvertTo-FwValue([string]$Type, [AllowEmptyString()][string]$Data) {
    $number=0; $bytes=$null
    switch -CaseSensitive ($Type) {
        'DWORD' { if ($Data -notmatch '^(0|[1-9][0-9]*)$') { throw 'DWORD requires unsigned decimal' }; $number=4; $bytes=[BitConverter]::GetBytes([uint32]::Parse($Data,[Globalization.CultureInfo]::InvariantCulture)) }
        'QWORD' { if ($Data -notmatch '^(0|[1-9][0-9]*)$') { throw 'QWORD requires unsigned decimal' }; $number=11; $bytes=[BitConverter]::GetBytes([uint64]::Parse($Data,[Globalization.CultureInfo]::InvariantCulture)) }
        { $_ -ceq 'SZ' -or $_ -ceq 'EXPAND_SZ' } {
            if ($Data.Contains([string][char]0)) { throw 'String contains NUL' }
            $number=1; if ($Type -ceq 'EXPAND_SZ') { $number=2 }
            $bytes=[Text.Encoding]::Unicode.GetBytes($Data + [char]0)
        }
        'MULTI_SZ' {
            if (-not $Data.TrimStart().StartsWith('[')) { throw 'MULTI_SZ requires JSON string array' }
            $items=ConvertFrom-Json -InputObject $Data
            if ($null -eq $items -or @($items).Count -eq 0) { throw 'MULTI_SZ empty array unsupported' }
            foreach ($item in $items) { if ($item -isnot [string] -or $item.Length -eq 0 -or $item.Contains([string][char]0)) { throw 'MULTI_SZ contains non-string, empty element or NUL' } }
            $number=7; $bytes=[Text.Encoding]::Unicode.GetBytes(($items -join [char]0) + [char]0 + [char]0)
        }
        default { throw 'Type must be DWORD, QWORD, SZ, EXPAND_SZ or MULTI_SZ (exact spelling)' }
    }
    [pscustomobject][ordered]@{ Exists=$true; Type=$number; Data=[Convert]::ToBase64String($bytes) }
}
function Assert-FwValue($v) {
    if ($null -eq $v -or $v.Exists -isnot [bool] -or $v.Type -notin @(0,1,2,3,4,7,11) -or $v.Data -isnot [string]) { throw 'Invalid value journal' }
    $bytes=[Convert]::FromBase64String($v.Data)
    if ([Convert]::ToBase64String($bytes) -cne $v.Data) { throw 'Invalid base64 journal' }
    if (-not $v.Exists) { if ($v.Type -ne 0 -or $v.Data -cne '') { throw 'Invalid absent journal value' }; return }
    if (($v.Type -eq 4 -and $bytes.Length -ne 4) -or ($v.Type -eq 11 -and $bytes.Length -ne 8)) { throw 'Invalid numeric journal value' }
    if ($bytes.Length -gt 1048576) { throw 'Journal value too large' }
}
function Test-FwValue($a,$b) { ($a.Exists -eq $b.Exists -and $a.Type -eq $b.Type -and $a.Data -ceq $b.Data) }
function Assert-FwOwner([string]$owner) { if ($owner -cnotmatch '^[a-z0-9][a-z0-9._-]{2,63}$') { throw 'Owner must be explicit, 3-64 lowercase ASCII letters/digits/dot/underscore/hyphen' } }
function Assert-FwTarget([string]$key,[string]$name) {
    if ($key -notmatch '^Software\\Policies\\[^\\]+(\\[^\\]+)*$' -or $key -match '[\x00-\x1f;*]' -or $key -ne $key.Trim() -or $key -match '(^|\\)\.\.?($|\\)') { throw 'Target must be a literal subkey of Software\Policies, without wildcards/control characters' }
    if ([string]::IsNullOrWhiteSpace($name) -or $name -match '[\x00-\x1f\\;*]' -or $name -eq '(Default)' -or $name -ne $name.Trim()) { throw 'Explicit literal nondefault value name required' }
}
function Get-FwHash([byte[]]$bytes) { $h=[Security.Cryptography.SHA256]::Create(); try { ([BitConverter]::ToString($h.ComputeHash($bytes))).Replace('-','').ToLowerInvariant() } finally { $h.Dispose() } }
function New-FwLedger { [pscustomobject][ordered]@{ Schema=1; Id=[guid]::NewGuid().ToString(); Records=@() } }
function Assert-FwLedger($s) {
    if ($s.Schema -ne 1 -or [string]::IsNullOrWhiteSpace($s.Id)) { throw 'Invalid journal schema' }
    $id=[guid]::Parse($s.Id); $owners=@{}; $targets=@{}
    foreach ($r in @($s.Records)) {
        Assert-FwOwner $r.Owner; Assert-FwTarget $r.Key $r.Name
        if ($owners.ContainsKey($r.Owner)) { throw 'Duplicate journal owner' }; $owners[$r.Owner]=$true
        if ($r.Phase -notin @('ApplyPolicy','ApplyRefresh','Active','RemovePolicy','RemoveRefresh','RestoreRegistry','Removed')) { throw 'Invalid journal phase' }
        foreach ($v in @($r.Desired,$r.OriginalPolicy,$r.OriginalRegistry,$r.RestoreBefore)) { Assert-FwValue $v }
        if (-not $r.Desired.Exists -or $r.Other -isnot [string] -or [string]::IsNullOrWhiteSpace($r.Backup)) { throw 'Invalid journal record' }
        if ($r.OriginalPolicy.Exists -and -not (Test-FwValue $r.OriginalPolicy $r.OriginalRegistry)) { throw 'Inconsistent original journal state' }
        if ($r.Phase -ne 'Removed') {
            $target=$r.Key.ToLowerInvariant() + '|' + $r.Name.ToLowerInvariant()
            if ($targets.ContainsKey($target)) { throw 'Duplicate target journal ownership' }; $targets[$target]=$true
        }
    }
}
function ConvertTo-FwEnvelope($s) {
    $payload=ConvertTo-Json -InputObject $s -Depth 20 -Compress
    $bytes=[Text.Encoding]::UTF8.GetBytes($payload)
    ConvertTo-Json -InputObject ([ordered]@{ sha256=(Get-FwHash $bytes); payload=[Convert]::ToBase64String($bytes) }) -Compress
}
function ConvertFrom-FwEnvelope([string]$text) {
    try {
        $e=ConvertFrom-Json -InputObject $text
        $bytes=[Convert]::FromBase64String($e.payload)
        if ((Get-FwHash $bytes) -cne $e.sha256) { throw 'checksum' }
        $s=ConvertFrom-Json -InputObject ([Text.UTF8Encoding]::new($false,$true).GetString($bytes))
        Assert-FwLedger $s; return $s
    } catch { throw "Invalid/corrupt journal: $($_.Exception.Message)" }
}
function Assert-FwExit([string]$command,[int]$code) { if ($code -ne 0) { throw "$command failed: $code" } }
function Assert-FwAllowed($actual,[object[]]$allowed,[string]$description) {
    foreach ($v in $allowed) { if (Test-FwValue $actual $v) { return } }
    throw "$description drift; refusing overwrite"
}
function Invoke-FwEngine {
    param([ValidateSet('Apply','Remove')][string]$Action, $Config, [hashtable]$IO, [switch]$Recover)
    Assert-FwOwner $Config.Owner
    if ($Action -eq 'Apply') { Assert-FwTarget $Config.Key $Config.Name; Assert-FwValue $Config.Desired; if (-not $Config.Desired.Exists) { throw 'Apply requires value' } }
    $locked=$false
    try {
        & $IO.Lock; $locked=$true
        $s=& $IO.Load; Assert-FwLedger $s
        $matches=@($s.Records | Where-Object { $_.Owner -ceq $Config.Owner })
        $r=$null; if ($matches.Count -gt 0) { $r=$matches[0] }
        if (@($s.Records | Where-Object { $_.Owner -cne $Config.Owner -and $_.Phase -notin @('Active','Removed') }).Count -gt 0) { throw 'Another owner has an interrupted transaction; recover it before other operations' }
        if ($null -eq $r) {
            if ($Action -eq 'Remove') { throw 'No saved owner state; removal refused' }
            foreach ($other in @($s.Records)) { if ($other.Phase -ne 'Removed' -and $other.Key -ieq $Config.Key -and $other.Name -ieq $Config.Name) { throw 'Target already owned by another owner' } }
            $before=& $IO.Read $Config.Key $Config.Name
            if ($before.Policy.Exists -and -not (Test-FwValue $before.Policy $before.Registry)) { throw 'Initial policy/effective registry mismatch; resolve competing manager before enrollment' }
            $backup=& $IO.Backup $Config.Owner
            $again=& $IO.Read $Config.Key $Config.Name
            if (-not (Test-FwValue $before.Policy $again.Policy) -or -not (Test-FwValue $before.Registry $again.Registry) -or $before.Other -cne $again.Other) { throw 'State drift during backup; no enrollment' }
            $r=[pscustomobject][ordered]@{ Owner=$Config.Owner; Key=$Config.Key; Name=$Config.Name; Desired=$Config.Desired; OriginalPolicy=$before.Policy; OriginalRegistry=$before.Registry; Phase='ApplyPolicy'; Other=$before.Other; Backup=$backup; RestoreBefore=(New-FwAbsent) }
            $s.Records=@($s.Records)+@($r); & $IO.Save $s
        } else {
            if ($Action -eq 'Apply' -and ($r.Key -ine $Config.Key -or $r.Name -ine $Config.Name -or -not (Test-FwValue $r.Desired $Config.Desired))) { throw 'Changed desired identity; remove original ownership explicitly before a new owner' }
            if ($r.Phase -eq 'Removed') { if ($Action -eq 'Apply') { throw 'Owner retired; use a new owner after reviewed removal' }; return 'AlreadyRemoved' }
            if ($r.Phase -eq 'Active') {
                $now=& $IO.Read $r.Key $r.Name
                Assert-FwAllowed $now.Policy @($r.Desired) 'Policy'; Assert-FwAllowed $now.Registry @($r.Desired) 'Registry'
                if ($Action -eq 'Apply') { return 'AlreadyApplied' }
                $r.Other=$now.Other; $r.Phase='RemovePolicy'; & $IO.Save $s
            } else {
                if (-not $Recover) { throw "Recovery required for $($r.Phase); inspect journal and retry same operation with explicit recovery" }
                if (($Action -eq 'Apply' -and $r.Phase -notlike 'Apply*') -or ($Action -eq 'Remove' -and $r.Phase -like 'Apply*')) { throw 'Recovery requires original operation first' }
            }
        }
        $now=& $IO.Read $r.Key $r.Name
        if ($now.Other -cne $r.Other) { throw 'unrelated policy drift during transaction; manual reconciliation required' }
        if ($Action -eq 'Apply') {
            Assert-FwAllowed $now.Registry @($r.OriginalRegistry,$r.Desired) 'Registry'
            if ($r.Phase -eq 'ApplyPolicy') {
                Assert-FwAllowed $now.Policy @($r.OriginalPolicy,$r.Desired) 'Policy'
                if (-not (Test-FwValue $now.Policy $r.Desired)) { & $IO.Policy $r.Key $r.Name $now.Policy $r.Desired $r.Other }
                $r.Phase='ApplyRefresh'; & $IO.Save $s
            }
            $now=& $IO.Read $r.Key $r.Name
            Assert-FwAllowed $now.Policy @($r.Desired) 'Policy'
            Assert-FwAllowed $now.Registry @($r.OriginalRegistry,$r.Desired) 'Registry'
            if ($now.Other -cne $r.Other) { throw 'unrelated policy drift' }
            & $IO.Refresh
            $now=& $IO.Read $r.Key $r.Name
            Assert-FwAllowed $now.Policy @($r.Desired) 'Policy'; Assert-FwAllowed $now.Registry @($r.Desired) 'Registry'
            if ($now.Other -cne $r.Other) { throw 'unrelated policy drift' }
            $r.Phase='Active'; & $IO.Save $s; return 'Applied'
        }
        $allowedRegistry=@($r.Desired,$r.OriginalRegistry)
        if (-not $r.OriginalPolicy.Exists) { $allowedRegistry+=@(New-FwAbsent) }
        Assert-FwAllowed $now.Registry $allowedRegistry 'Registry'
        if ($r.Phase -eq 'RemovePolicy') {
            Assert-FwAllowed $now.Policy @($r.Desired,$r.OriginalPolicy) 'Policy'
            if (-not (Test-FwValue $now.Policy $r.OriginalPolicy)) { & $IO.Policy $r.Key $r.Name $now.Policy $r.OriginalPolicy $r.Other }
            $r.Phase='RemoveRefresh'; & $IO.Save $s
        }
        $now=& $IO.Read $r.Key $r.Name
        Assert-FwAllowed $now.Policy @($r.OriginalPolicy) 'Policy'
        Assert-FwAllowed $now.Registry $allowedRegistry 'Registry'
        if ($now.Other -cne $r.Other) { throw 'unrelated policy drift' }
        if ($r.Phase -eq 'RemoveRefresh') {
            & $IO.Refresh
            $now=& $IO.Read $r.Key $r.Name
            Assert-FwAllowed $now.Policy @($r.OriginalPolicy) 'Policy'; Assert-FwAllowed $now.Registry $allowedRegistry 'Registry'
            if ($now.Other -cne $r.Other) { throw 'unrelated policy drift' }
            $r.RestoreBefore=$now.Registry; $r.Phase='RestoreRegistry'; & $IO.Save $s
        }
        Assert-FwAllowed $now.Registry @($r.RestoreBefore,$r.OriginalRegistry) 'Registry'
        if (-not (Test-FwValue $now.Registry $r.OriginalRegistry)) { & $IO.Registry $r.Key $r.Name $now.Registry $r.OriginalRegistry }
        $now=& $IO.Read $r.Key $r.Name
        Assert-FwAllowed $now.Policy @($r.OriginalPolicy) 'Policy'; Assert-FwAllowed $now.Registry @($r.OriginalRegistry) 'Registry'
        if ($now.Other -cne $r.Other) { throw 'unrelated policy drift' }
        $r.Phase='Removed'; & $IO.Save $s; return 'Removed'
    } finally { if ($locked) { & $IO.Unlock } }
}

# Native source is compiled only by Initialize-FwNative; no native call occurs at import.
$script:FwNativeSource = @'
using System;
using System.Text;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
namespace FwPolicyReview {
    [ComImport, Guid("EA502723-A23D-11D1-A7D3-0000F87571E3"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    interface IGpo {
        void New([MarshalAs(UnmanagedType.LPWStr)] string domain, [MarshalAs(UnmanagedType.LPWStr)] string display, uint flags);
        void OpenDSGPO([MarshalAs(UnmanagedType.LPWStr)] string path, uint flags);
        void OpenLocalMachineGPO(uint flags);
        void OpenRemoteMachineGPO([MarshalAs(UnmanagedType.LPWStr)] string computer, uint flags);
        void Save([MarshalAs(UnmanagedType.Bool)] bool machine, [MarshalAs(UnmanagedType.Bool)] bool add, ref Guid extension, ref Guid editor);
        void Delete();
        void GetName([MarshalAs(UnmanagedType.LPWStr)] StringBuilder name, int length);
        void GetDisplayName([MarshalAs(UnmanagedType.LPWStr)] StringBuilder name, int length);
        void SetDisplayName([MarshalAs(UnmanagedType.LPWStr)] string name);
        void GetPath([MarshalAs(UnmanagedType.LPWStr)] StringBuilder path, int length);
        void GetDSPath(uint section, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder path, int length);
        void GetFileSysPath(uint section, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder path, int length);
        void GetRegistryKey(uint section, out IntPtr handle);
        void GetOptions(out uint options);
        void SetOptions(uint options, uint mask);
        void GetType(out uint type);
        void GetMachineName([MarshalAs(UnmanagedType.LPWStr)] StringBuilder name, int length);
        void GetPropertySheetPages(out IntPtr pages, out uint count);
    }
    public sealed class RawValue {
        public bool Exists; public uint Type; public string Data;
        public RawValue() { Exists=false; Type=0; Data=""; }
        public RawValue(bool exists, uint type, string data) { Exists=exists; Type=type; Data=data; }
    }
    public sealed class Snapshot { public RawValue Policy; public RawValue Registry; public string Other; }
    public static class Native {
        [DllImport("advapi32.dll", CharSet=CharSet.Unicode)] static extern int RegQueryValueEx(IntPtr key, string name, IntPtr reserved, out uint type, byte[] data, ref uint size);
        [DllImport("advapi32.dll", CharSet=CharSet.Unicode)] static extern int RegSetValueEx(IntPtr key, string name, int reserved, uint type, byte[] data, int size);
        [DllImport("advapi32.dll", CharSet=CharSet.Unicode)] static extern int RegDeleteValue(IntPtr key, string name);
        [DllImport("userenv.dll", SetLastError=true)] static extern IntPtr EnterCriticalPolicySection([MarshalAs(UnmanagedType.Bool)] bool machine);
        [DllImport("userenv.dll", SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] static extern bool LeaveCriticalPolicySection(IntPtr handle);
        [DllImport("advapi32.dll", CharSet=CharSet.Unicode, SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] static extern bool ConvertStringSecurityDescriptorToSecurityDescriptor(string sddl, uint revision, out IntPtr descriptor, out uint length);
        [StructLayout(LayoutKind.Sequential)] struct SECURITY_ATTRIBUTES { public int Length; public IntPtr Descriptor; public int Inherit; }
        [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] static extern bool CreateDirectory(string path, ref SECURITY_ATTRIBUTES attributes);
        [DllImport("kernel32.dll")] static extern IntPtr LocalFree(IntPtr ptr);
        public static void CreateProtectedDirectory(string path) {
            IntPtr sd; uint length;
            if (!ConvertStringSecurityDescriptorToSecurityDescriptor("O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)",1,out sd,out length)) throw new Win32Exception();
            try { SECURITY_ATTRIBUTES sa=new SECURITY_ATTRIBUTES(); sa.Length=Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES)); sa.Descriptor=sd;
                if (!CreateDirectory(path,ref sa)) throw new Win32Exception();
            } finally { LocalFree(sd); }
        }
        sealed class Critical : IDisposable {
            IntPtr handle;
            public Critical() { handle=EnterCriticalPolicySection(true); if(handle==IntPtr.Zero) throw new Win32Exception(); }
            public void Dispose() { if(handle!=IntPtr.Zero) { IntPtr h=handle; handle=IntPtr.Zero; if(!LeaveCriticalPolicySection(h)) throw new Win32Exception(); } }
        }
        sealed class Gpo : IDisposable {
            public IGpo Object; public RegistryKey Root;
            public Gpo(bool readOnly) {
                try {
                    Object=(IGpo)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("EA502722-A23D-11D1-A7D3-0000F87571E3"),true));
                    Object.OpenLocalMachineGPO(readOnly ? 3u : 1u);
                    uint options; Object.GetOptions(out options); if((options & 2)!=0) throw new InvalidOperationException("Computer GPO disabled; refusing mutation");
                    IntPtr h; Object.GetRegistryKey(2,out h); Root=RegistryKey.FromHandle(new SafeRegistryHandle(h,true));
                } catch { Dispose(); throw; }
            }
            public void Dispose() { if(Root!=null) { Root.Dispose(); Root=null; } if(Object!=null) { Marshal.FinalReleaseComObject(Object); Object=null; } }
        }
        static void Check(int code) { if(code!=0) throw new Win32Exception(code); }
        static RawValue ReadValue(RegistryKey root,string key,string name) {
            using(RegistryKey sub=key.Length==0 ? null : root.OpenSubKey(key,false)) {
                RegistryKey k=key.Length==0 ? root : sub; if(k==null) return new RawValue();
                uint type; uint size=0; IntPtr h=k.Handle.DangerousGetHandle(); int result=RegQueryValueEx(h,name,IntPtr.Zero,out type,null,ref size);
                if(result==2) return new RawValue(); Check(result); if(size>1048576) throw new InvalidOperationException("Registry value exceeds bounded size");
                byte[] bytes=new byte[size]; Check(RegQueryValueEx(h,name,IntPtr.Zero,out type,bytes,ref size));
                if(size!=bytes.Length) Array.Resize(ref bytes,(int)size);
                return new RawValue(true,type,Convert.ToBase64String(bytes));
            }
        }
        static bool Equal(RawValue a,RawValue b) { return a.Exists==b.Exists && a.Type==b.Type && a.Data==b.Data; }
        static void WriteValue(RegistryKey root,string key,string name,RawValue value) {
            if(value.Exists) {
                using(RegistryKey sub=root.CreateSubKey(key)) { byte[] bytes=Convert.FromBase64String(value.Data); Check(RegSetValueEx(sub.Handle.DangerousGetHandle(),name,0,value.Type,bytes,bytes.Length)); }
            } else {
                using(RegistryKey sub=root.OpenSubKey(key,true)) { if(sub==null) return; int code=RegDeleteValue(sub.Handle.DangerousGetHandle(),name); if(code!=2) Check(code); }
            }
        }
        static void Walk(RegistryKey root,RegistryKey node,string path,SortedDictionary<string,string> values,string targetKey,string targetName) {
            foreach(string name in node.GetValueNames()) {
                // Conservative admission: ANY special registry-policy directive anywhere blocks this candidate.
                if(name.StartsWith("**",StringComparison.Ordinal)) throw new InvalidOperationException("Special policy directive present; manual review required");
                if(string.Equals(path,targetKey,StringComparison.OrdinalIgnoreCase) && string.Equals(name,targetName,StringComparison.OrdinalIgnoreCase)) continue;
                RawValue v=ReadValue(root,path,name);
                if(!v.Exists) throw new InvalidOperationException("Concurrent policy enumeration change");
                string identity=path.ToUpperInvariant()+"\0"+name.ToUpperInvariant();
                values.Add(identity,v.Type.ToString(System.Globalization.CultureInfo.InvariantCulture)+":"+v.Data);
            }
            foreach(string name in node.GetSubKeyNames()) {
                using(RegistryKey child=node.OpenSubKey(name,false)) { if(child==null) throw new InvalidOperationException("Concurrent policy enumeration change"); Walk(root,child,path.Length==0 ? name : path+"\\"+name,values,targetKey,targetName); }
            }
        }
        static string Other(RegistryKey root,string key,string name) {
            SortedDictionary<string,string> values=new SortedDictionary<string,string>(StringComparer.Ordinal);
            Walk(root,root,"",values,key,name);
            StringBuilder b=new StringBuilder(); foreach(KeyValuePair<string,string> p in values) { b.Append(p.Key.Length).Append(':').Append(p.Key).Append(p.Value.Length).Append(':').Append(p.Value); }
            using(SHA256 hash=SHA256.Create()) return Convert.ToBase64String(hash.ComputeHash(Encoding.UTF8.GetBytes(b.ToString())));
        }
        static string Stamp() {
            string basePath=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows),"System32","GroupPolicy");
            string[] paths={Path.Combine(basePath,"Machine","Registry.pol"),Path.Combine(basePath,"gpt.ini")};
            StringBuilder b=new StringBuilder(); foreach(string path in paths) { if(File.Exists(path)) { using(SHA256 hash=SHA256.Create()) { using(FileStream stream=File.OpenRead(path)) b.Append(Convert.ToBase64String(hash.ComputeHash(stream))); } } else b.Append("absent"); b.Append('|'); }
            return b.ToString();
        }
        public static Snapshot Read(string key,string name) {
            using(Critical guard=new Critical()) {
                string stamp=Stamp();
                using(Gpo g=new Gpo(true)) using(RegistryKey hklm=RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,RegistryView.Registry64)) {
                    Snapshot s=new Snapshot(); s.Policy=ReadValue(g.Root,key,name); s.Registry=ReadValue(hklm,key,name); s.Other=Other(g.Root,key,name);
                    if(Stamp()!=stamp) throw new InvalidOperationException("Policy files changed during read"); return s;
                }
            }
        }
        public static void Policy(string key,string name,RawValue before,RawValue after,string expectedOther) {
            using(Critical guard=new Critical()) {
                string stamp=Stamp();
                using(Gpo g=new Gpo(false)) {
                    if(!Equal(ReadValue(g.Root,key,name),before) || Other(g.Root,key,name)!=expectedOther || Stamp()!=stamp) throw new InvalidOperationException("Policy drift before write");
                    WriteValue(g.Root,key,name,after);
                    if(!Equal(ReadValue(g.Root,key,name),after) || Other(g.Root,key,name)!=expectedOther || Stamp()!=stamp) throw new InvalidOperationException("Policy drift before Save; not saved");
                    Guid extension=new Guid("35378EAC-683F-11D2-A89A-00C04FBBCFA2"); Guid editor=new Guid("8FC0B734-A0E1-11D1-A7D3-0000F87571E3");
                    // Retained empty keys are still registry settings. Never unregister other settings' CSE.
                    bool add=g.Root.ValueCount!=0 || g.Root.SubKeyCount!=0;
                    g.Object.Save(true,add,ref extension,ref editor);
                }
                using(Gpo verify=new Gpo(true)) {
                    if(!Equal(ReadValue(verify.Root,key,name),after) || Other(verify.Root,key,name)!=expectedOther) throw new InvalidOperationException("Policy post-save verification failed");
                }
            }
        }
        public static void Registry(string key,string name,RawValue before,RawValue after) {
            using(Critical guard=new Critical()) using(RegistryKey root=RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,RegistryView.Registry64)) {
                if(!Equal(ReadValue(root,key,name),before)) throw new InvalidOperationException("Registry drift before restoration");
                WriteValue(root,key,name,after);
                if(!Equal(ReadValue(root,key,name),after)) throw new InvalidOperationException("Registry restoration verification failed");
            }
        }
    }
}
'@
function Initialize-FwNative { if (-not ('FwPolicyReview.Native' -as [type])) { Add-Type -TypeDefinition $script:FwNativeSource -Language CSharp } }
function ConvertTo-FwNativeValue($v) { [FwPolicyReview.RawValue]::new([bool]$v.Exists,[uint32]$v.Type,[string]$v.Data) }

function Assert-FwNoReparse([string]$path) {
    $full=[IO.Path]::GetFullPath($path)
    if ($full -notmatch '^[A-Za-z]:\\') { throw 'Only local drive paths are admitted' }
    $part=$full
    while ($part) {
        if (Test-Path -LiteralPath $part) {
            $item=Get-Item -LiteralPath $part -Force
            if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw "Reparse point refused: $part" }
        }
        $parent=[IO.Directory]::GetParent($part); if ($null -eq $parent) { break }; $part=$parent.FullName
    }
}
function Assert-FwProtected([string]$path,[switch]$Root) {
    Assert-FwNoReparse $path
    if (-not (Test-Path -LiteralPath $path)) { throw "Missing protected path: $path" }
    $acl=Get-Acl -LiteralPath $path
    $trusted=@('S-1-5-18','S-1-5-32-544')
    if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -notin $trusted) { throw "Untrusted journal owner: $path" }
    if ($Root -and -not $acl.AreAccessRulesProtected) { throw 'Journal root must disable ACL inheritance' }
    $seen=@{}
    foreach ($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])) {
        $sid=$rule.IdentityReference.Value
        if ($rule.AccessControlType -ne [Security.AccessControl.AccessControlType]::Allow -or $sid -notin $trusted) { throw "Unexpected journal ACL: $path" }
        if (($rule.FileSystemRights -band [Security.AccessControl.FileSystemRights]::FullControl) -ne [Security.AccessControl.FileSystemRights]::FullControl) { throw "Incomplete journal ACL: $path" }
        $seen[$sid]=$true
    }
    foreach ($sid in $trusted) { if (-not $seen.ContainsKey($sid)) { throw "Missing journal ACL principal: $path" } }
}
function Assert-FwParentProtection([string]$path) {
    Assert-FwNoReparse $path
    $part=[IO.Directory]::GetParent($path)
    $trusted=@('S-1-5-18','S-1-5-32-544','S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464')
    while ($null -ne $part) {
        $acl=Get-Acl -LiteralPath $part.FullName
        if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -notin $trusted) { throw 'Untrusted journal ancestor owner' }
        foreach ($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])) {
            if ($rule.AccessControlType -eq [Security.AccessControl.AccessControlType]::Allow -and $rule.IdentityReference.Value -notin $trusted -and ($rule.PropagationFlags -band [Security.AccessControl.PropagationFlags]::InheritOnly) -eq 0) {
                $danger=[Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles -bor [Security.AccessControl.FileSystemRights]::ChangePermissions -bor [Security.AccessControl.FileSystemRights]::TakeOwnership
                if (($rule.FileSystemRights -band $danger) -ne 0) { throw 'Untrusted journal ancestor delete/ACL permission' }
            }
        }
        $part=$part.Parent
    }
}
function Write-FwLedgerFile([string]$root,$ledger,[switch]$Initial) {
    Assert-FwProtected $root -Root; Assert-FwLedger $ledger
    $path=Join-Path $root 'journal.json'; $next=Join-Path $root 'journal.next'
    if (Test-Path -LiteralPath $next) { throw 'Uncommitted journal.next exists; manual inspection required' }
    $text=ConvertTo-FwEnvelope $ledger; $bytes=[Text.Encoding]::UTF8.GetBytes($text)
    $stream=[IO.FileStream]::new($next,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::None,4096,[IO.FileOptions]::WriteThrough)
    try { $stream.Write($bytes,0,$bytes.Length); $stream.Flush($true) } finally { $stream.Dispose() }
    Assert-FwProtected $next
    if ($Initial) { [IO.File]::Move($next,$path) } else { Assert-FwProtected $path; [IO.File]::Replace($next,$path,[NullString]::Value) }
    Assert-FwProtected $path
    if ([IO.File]::ReadAllText($path,[Text.Encoding]::UTF8) -cne $text) { throw 'Journal readback mismatch' }
    $null=ConvertFrom-FwEnvelope ([IO.File]::ReadAllText($path,[Text.Encoding]::UTF8))
}
function Read-FwLedgerFile([string]$root) {
    Assert-FwParentProtection $root; Assert-FwProtected $root -Root
    if (Test-Path -LiteralPath (Join-Path $root 'journal.next')) { throw 'Uncommitted journal.next exists; manual inspection required' }
    $path=Join-Path $root 'journal.json'; Assert-FwProtected $path
    if ((Get-Item -LiteralPath $path).Length -gt 16777216) { throw 'Journal exceeds bounded size' }
    $s=ConvertFrom-FwEnvelope ([IO.File]::ReadAllText($path,[Text.UTF8Encoding]::new($false,$true)))
    foreach ($record in @($s.Records)) {
        if ($record.Backup -cnotmatch '^backup-[a-z0-9._-]+-[a-f0-9-]{36}$') { throw 'Invalid backup journal path' }
        $backup=Join-Path $root $record.Backup; Assert-FwProtected $backup
        $manifestPath=Join-Path $backup 'manifest.json'; Assert-FwProtected $manifestPath
        $manifest=ConvertFrom-Json -InputObject ([IO.File]::ReadAllText($manifestPath))
        if (@($manifest).Count -eq 0) { throw 'Missing backup manifest data' }
        foreach ($entry in @($manifest)) {
            if ([IO.Path]::IsPathRooted($entry.Path) -or $entry.Path -match '(^|[\\/])\.\.([\\/]|$)') { throw 'Invalid backup manifest path' }
            $file=Join-Path $backup $entry.Path; Assert-FwProtected $file
            if ((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash -ine $entry.SHA256) { throw 'Corrupt original LGPO backup' }
        }
    }
    return $s
}
function Invoke-FwNativeCommand([string]$executable,[string[]]$arguments) {
    # No shell and no untrusted argument interpolation. All current arguments are fixed switches or locally-generated paths.
    $quoted=@(); foreach ($arg in $arguments) {
        if ($arg.Contains('"') -or $arg.EndsWith('\')) { throw 'Unsupported native argument quoting' }
        $quoted+=('"'+$arg+'"')
    }
    $p=[Diagnostics.Process]::new(); $p.StartInfo.FileName=$executable; $p.StartInfo.Arguments=$quoted -join ' '
    $p.StartInfo.UseShellExecute=$false; $p.StartInfo.CreateNoWindow=$true
    try {
        if (-not $p.Start()) { throw 'Native process could not start' }
        if (-not $p.WaitForExit(180000)) { throw 'Native command timeout; child may still be running; do NOT retry until inspected' }
        Assert-FwExit ([IO.Path]::GetFileName($executable)) $p.ExitCode
    } finally { $p.Dispose() }
}
function New-FwWindowsIO([string]$root,[string]$lgpo,[string]$gpupdate) {
    $context=@{ Root=$root; LGPO=$lgpo; GPUpdate=$gpupdate; Lock=$null }
    @{
        Lock = {
            Assert-FwParentProtection $context.Root; Assert-FwProtected $context.Root -Root
            $lockPath=Join-Path $context.Root 'operation.lock'
            if (Test-Path -LiteralPath $lockPath) { Assert-FwProtected $lockPath }
            $context.Lock=[IO.File]::Open($lockPath,[IO.FileMode]::OpenOrCreate,[IO.FileAccess]::ReadWrite,[IO.FileShare]::None)
        }.GetNewClosure()
        Unlock = { if ($null -ne $context.Lock) { $context.Lock.Dispose(); $context.Lock=$null } }.GetNewClosure()
        Load = { Read-FwLedgerFile $context.Root }.GetNewClosure()
        Save = { param($s) Write-FwLedgerFile $context.Root $s }.GetNewClosure()
        Read = { param($key,$name) [FwPolicyReview.Native]::Read($key,$name) }
        Policy = { param($key,$name,$before,$after,$other) [FwPolicyReview.Native]::Policy($key,$name,(ConvertTo-FwNativeValue $before),(ConvertTo-FwNativeValue $after),$other) }
        Registry = { param($key,$name,$before,$after) [FwPolicyReview.Native]::Registry($key,$name,(ConvertTo-FwNativeValue $before),(ConvertTo-FwNativeValue $after)) }
        Refresh = { Invoke-FwNativeCommand $context.GPUpdate @('/target:computer','/force','/wait:120') }.GetNewClosure()
        Backup = {
            param($owner)
            $relative='backup-'+$owner+'-'+[guid]::NewGuid().ToString(); $backup=Join-Path $context.Root $relative
            [FwPolicyReview.Native]::CreateProtectedDirectory($backup); Assert-FwProtected $backup
            Invoke-FwNativeCommand $context.LGPO @('/b',$backup)
            $files=@(Get-ChildItem -LiteralPath $backup -Recurse -File -Force)
            if (@($files | Where-Object { $_.Name -ieq 'Backup.xml' }).Count -ne 1 -or @($files | Where-Object { $_.Name -ieq 'Registry.pol' -and $_.Directory.Name -ieq 'Machine' }).Count -ne 1) { throw 'LGPO backup missing expected files' }
            $manifest=@(); foreach ($file in $files) {
                Assert-FwProtected $file.FullName
                $manifest+=@([pscustomobject]@{ Path=$file.FullName.Substring($backup.Length+1); SHA256=(Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash })
            }
            [IO.File]::WriteAllText((Join-Path $backup 'manifest.json'),(ConvertTo-Json -InputObject $manifest -Depth 5),[Text.Encoding]::UTF8)
            return $relative
        }.GetNewClosure()
    }
}
function Get-FwEnvironment([string]$name) { [Environment]::GetEnvironmentVariable($name,[EnvironmentVariableTarget]::Process) }
function Invoke-FwMain([ValidateSet('Apply','Remove','Initialize')][string]$Action) {
    # Disabled payloads return nonzero; they must never be reported as applied.
    if ((Get-FwEnvironment 'FW_POLICY_ENABLED') -cne 'true') { throw 'Disabled template: explicitly set FW_POLICY_ENABLED=true only for approved deployment' }
    if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT -or -not [Environment]::Is64BitProcess -or -not [Environment]::Is64BitOperatingSystem -or $PSVersionTable.PSVersion -lt [version]'5.1') { throw 'Requires elevated 64-bit Windows PowerShell 5.1 or later on Windows' }
    if ([Threading.Thread]::CurrentThread.GetApartmentState() -ne [Threading.ApartmentState]::STA) { throw 'Launch PowerShell with -STA for Group Policy COM' }
    $identity=[Security.Principal.WindowsIdentity]::GetCurrent(); $principal=[Security.Principal.WindowsPrincipal]::new($identity)
    if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Elevation/SYSTEM required' }
    if ((Get-FwEnvironment 'FW_POLICY_EXCLUSIVE') -cne 'true') { throw 'FW_POLICY_EXCLUSIVE=true must acknowledge isolated deployment; no competing writers' }
    if ((Get-CimInstance -ClassName Win32_ComputerSystem).PartOfDomain) { throw 'Domain-joined computers excluded from this bounded template' }
    $scope=Get-FwEnvironment 'FW_POLICY_SCOPE'; if ($scope -and $scope -cne 'Computer') { throw 'Only Computer scope supported' }
    $recover=Get-FwEnvironment 'FW_POLICY_RECOVER'; if ($recover -and $recover -cnotin @('true','false')) { throw 'FW_POLICY_RECOVER must be true or false' }
    $root=Join-Path ([Environment]::GetFolderPath([Environment+SpecialFolder]::CommonApplicationData)) 'FileWavePolicyJournal-review-v1'
    Assert-FwParentProtection $root
    Initialize-FwNative
    if ($Action -eq 'Initialize') {
        # Manual provisioning ONLY. Never called by lifecycle scripts. Existing/partial root is never reset.
        if (Test-Path -LiteralPath $root) { throw 'Journal root already exists; initialization refused (never delete state to retry)' }
        [FwPolicyReview.Native]::CreateProtectedDirectory($root)
        Write-FwLedgerFile $root (New-FwLedger) -Initial
        $null=Read-FwLedgerFile $root
        Write-Output "Initialized empty protected journal: $root"; return
    }
    $owner=Get-FwEnvironment 'FW_POLICY_OWNER'; Assert-FwOwner $owner
    $config=[pscustomobject]@{ Owner=$owner; Key=''; Name=''; Desired=$null }
    if ($Action -eq 'Apply') {
        $config.Key=Get-FwEnvironment 'FW_POLICY_KEY'; $config.Name=Get-FwEnvironment 'FW_POLICY_VALUE'; Assert-FwTarget $config.Key $config.Name
        $data=Get-FwEnvironment 'FW_POLICY_DATA'; if ($null -eq $data) { throw 'Explicit FW_POLICY_DATA required' }
        $config.Desired=ConvertTo-FwValue (Get-FwEnvironment 'FW_POLICY_TYPE') $data
    }
    $lgpo=Get-FwEnvironment 'FW_LGPO_EXE'
    if ([string]::IsNullOrWhiteSpace($lgpo) -or -not [IO.Path]::IsPathRooted($lgpo)) { throw 'Explicit absolute FW_LGPO_EXE required on apply AND removal' }
    Assert-FwNoReparse $lgpo
    if (-not (Test-Path -LiteralPath $lgpo -PathType Leaf)) { throw 'Missing LGPO.exe; no fallback' }
    $sig=Get-AuthenticodeSignature -LiteralPath $lgpo
    if ($sig.Status -ne 'Valid' -or $null -eq $sig.SignerCertificate -or $sig.SignerCertificate.Subject -notmatch '(^|,\s*)O=Microsoft Corporation(,|$)') { throw 'LGPO must have a valid Microsoft Authenticode signature' }
    $gpupdate=Join-Path ([Environment]::GetFolderPath([Environment+SpecialFolder]::Windows)) 'System32\gpupdate.exe'
    Assert-FwNoReparse $gpupdate; if (-not (Test-Path -LiteralPath $gpupdate -PathType Leaf)) { throw 'Missing gpupdate.exe' }
    $io=New-FwWindowsIO $root $lgpo $gpupdate
    Invoke-FwEngine -Action $Action -Config $config -IO $io -Recover:($recover -ceq 'true')
}

if (-not $LibraryOnly) {
    try { Invoke-FwMain -Action $Mode; exit 0 }
    catch { Write-Error -Message ("LGPO policy stopped: " + $_.Exception.Message) -ErrorAction Continue; exit 1 }
}
